﻿///////////////////////////////////////////////////
//项目：基于手机蓝牙的可配置的计算机应用程序遥控
//作者：华南理工：曹炼强 林伟彬
//本文件功能：主窗口，控制蓝牙蓝牙发布、关闭
//////////////////////////////////////////////////
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using Microsoft.Win32;
using System.Security.Cryptography;

namespace BCC
{
    public partial class MainForm : Form
    {
        //用于控制程序的类对象
        private Control controler = new Control();
        private Thread serverThread;
        private Thread recvThread;
        public int msecond = 10;
        public MainForm()
        {
            InitializeComponent();
            MainForm.CheckForIllegalCrossThreadCalls = false;
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = "请先从左边列表选择一个配置文件，然后开启服务";
            load_checkedListData();
            button_service_Click(sender, e);
        }
        private void load_checkedListData()
        {
            checkedListBox_files.Items.Clear();
            string dirpath;
            DirectoryInfo dir;
            FileInfo[] xmlfiles;
            try
            {
                dirpath = Application.StartupPath + "/data";
                if (!Directory.Exists(dirpath))
                {
                    Directory.CreateDirectory(dirpath);
                    return;
                }
                dir = new DirectoryInfo(dirpath);
                xmlfiles = dir.GetFiles("*.xml");
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载配置文件异常！请重启程序！"+ex.Message);
                this.Close();
                return;
            }
            //listBox1.DataSource = bmpfiles;
            int n = xmlfiles.Length;
            if (n == 0)
                return;
            checkedListBox_files.BeginUpdate();
            for (int i = 0; i < n; i++)
            {
                checkedListBox_files.Items.Add(xmlfiles[i].Name + " <" + xmlfiles[i].CreationTime + ">");
            }
            checkedListBox_files.EndUpdate();
            this.checkedListBox_files.SetSelected(0, true);
            this.setListBox_files_SelectedIndexChecked(0);
        }
        private void setListBox_files_SelectedIndexChecked(int index)
        {
            this.checkedListBox_files.SetItemChecked(index, true);
        }
        private void setListBox_files_CheckedStatus_Unchecked()
        {
            for (int i = 0; i < checkedListBox_files.Items.Count; i++)
            {
                this.checkedListBox_files.SetItemCheckState(i, CheckState.Unchecked);
            }
        }
        private void checkedListBox_files_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            if (checkedListBox_files.CheckedItems.Count > 0)
            {
                setListBox_files_CheckedStatus_Unchecked();
                this.setListBox_files_SelectedIndexChecked(this.checkedListBox_files.SelectedIndex);
            }
        }

        private void button_service_Click(object sender, EventArgs e)
        {
            serverThread = new Thread(new ThreadStart(this.contrlServer));
            //serverThread.Name = "serverThread";

            recvThread = new Thread(new ThreadStart(this.rcv));
            if (button_service.Text.Equals("断开"))
            {
                //xmlClass xml = new xmlClass();
                //string sendStr = xml.findKeyValue("data.xml", "test.ppt");;
                // sendStr = sendStr;

                toolStripStatusLabel1.Text = "准备关闭蓝牙服务...";
                int b = Server.Close();
                Server.BluetoothEnableDiscovery((IntPtr)0, false);
                if (b == 1)
                    toolStripStatusLabel1.Text = "关闭蓝牙服务成功...";
                else
                    toolStripStatusLabel1.Text = "关闭蓝牙服务出错...";
                recvThread.Abort();
                serverThread.Abort();
                button_service.Text = "连接";
                try
                {
                    Bitmap logon_but = new Bitmap(Application.StartupPath + "//img//logo_start.jpg");
                    Bitmap logon_pic = new Bitmap(Application.StartupPath + "//img//unconnected.jpg");
                    //Bitmap logon_ntf = new Bitmap("img//ico2.ico");
                    button_service.Image = logon_but;
                    pictureBox1.Image = logon_pic;
                    this.Icon = new Icon(Application.StartupPath + "//img//logo_off.ico");
                    notifyIcon1.Icon = new Icon(Application.StartupPath + "//img//16-1.ico");
                }
                catch (Exception e2)
                {
                    MessageBox.Show("程序图片资源丢失！无法正常显示！"+e2.Message);
                    //this.Close();
                    return;
                }
            }
            else if(button_service.Text.Equals("连接"))
            {
                serverThread.Start();
                
                this.MenuItem_Enable.Text = "注销";
                Console.WriteLine(serverThread.Name);
                Console.WriteLine(serverThread.ThreadState);
                button_service.Text = "断开";
                try
                {
                    Bitmap logout_but = new Bitmap(Application.StartupPath + "//img//logo_stop.jpg");
                    Bitmap logout_pic = new Bitmap(Application.StartupPath + "//img//connected.jpg");
                    //Bitmap logout_ntf = new Bitmap("img//ico4.ico");
                    button_service.Image = logout_but;
                    pictureBox1.Image = logout_pic;
                    this.Icon = new Icon(Application.StartupPath + "//img//logo_on.ico");
                    notifyIcon1.Icon = new Icon(Application.StartupPath + "//img//16-2.ico");
                }
                catch (Exception e3)
                {
                    MessageBox.Show("程序图片资源丢失！无法正常显示！"+e3.Message);
                    //this.Close();
                    return;
                }
            }

        }

        private void button_edit_Click(object sender, EventArgs e)
        {
            string xmlName = checkedListBox_files.SelectedItem.ToString();
            if (xmlName == null)
            {
                MessageBox.Show("请先从左边列表中选择一个配置文件！");
                return;
            }
            string[] sArray = xmlName.Split('.');
            xmlName = sArray[0];
            SetForm setform = new SetForm();
            setform.fileName = xmlName+".xml";
            setform.ShowDialog();

        }

        private void button_new_Click(object sender, EventArgs e)
        {
            if (button_new.Text.Equals("新建"))
            {
                button_edit.Visible = false;
                button_pwd.Visible = false;
                fileName_text.Visible = true;
                button_new.Text = "确定";
                button_del.Text = "取消";
                toolStripStatusLabel1.Text = "请在文本框内输入新建文件名称";
               
            }
            else if(button_new.Text.Equals("确定")) 
            {
                string fileName = fileName_text.Text;
                if (!fileName.Equals(""))
                {
                    string[] sArray = fileName.Split('.');
                    fileName = sArray[0] + ".xml";
                    try
                    {
                        string dirpath = Application.StartupPath + "/data/" + fileName;
                        FileInfo file = new FileInfo(dirpath);
                        if (file.Exists)
                        {
                            MessageBox.Show("该文件已存在，请重新命名！");                  
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("加载配置文件异常！请重启程序！"+ex.Message);
                        this.Close();
                        return;
                    }
                    
                    xmlClass xml;
                    try
                    {
                        xml = new xmlClass();
                        xml.creatXmldoc(fileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("新建xml文件错误！系统信息：" + ex.ToString());
                    }
                    load_checkedListData();
                    button_new.Text = "新建";
                    button_edit.Visible = true;
                    button_pwd.Visible = true;
                    button_del.Text = "删除";
                    fileName_text.Visible = false;
                    toolStripStatusLabel1.Text = "添加成功，请选择该项后点击编辑按钮进行编辑";
                }
                else {
                    MessageBox.Show("请在文本框中输入文件名");
                    fileName_text.Focus();
                    return;
                }
            }
        }
        

        private void button_del_Click(object sender, EventArgs e)
        {
            if (button_del.Text.Equals("删除"))
            {
                string xmlName = checkedListBox_files.SelectedItem.ToString();
                if (xmlName == null)
                {
                    MessageBox.Show("请先从左边列表中选择一个配置文件！");
                    return;
                }
                string[] sArray = xmlName.Split('.');
                xmlName = sArray[0] + ".xml";
                DialogResult dr = MessageBox.Show("确定删除" + xmlName + "配置文件？", "配置文件删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
                if ((int)dr == 1)
                {
                    string dirpath = Application.StartupPath + "/data/" + xmlName;
                    try
                    {
                        FileInfo file = new FileInfo(dirpath);

                        if (file.Exists)
                        {
                            file.Delete(); //删除单个文件
                        }
                        else
                        {
                            MessageBox.Show("该文件不存在！");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("删除文件失败！系统信息：" + ex.ToString());
                    }
                }
                load_checkedListData();
            }
            else if (button_del.Text.Equals("取消"))
            {
                button_new.Text = "新建";
                button_edit.Visible = true;
                button_pwd.Visible = true;
                button_del.Text = "删除";
                fileName_text.Visible = false;
            }
            else if (button_del.Text.Equals("确定"))
            {
                string pwdfileName = "Password.txt";
                string dirpath = Application.StartupPath + "/data/" + pwdfileName;

                StreamReader sr = new StreamReader(dirpath);
                string pwd0 = sr.ReadToEnd();
                sr.Close();

                if (pwd0.Equals("d41d8cd98f0b24e980998ecf8427e")) //密码为空的界面
                {
                    string pwd1 = fileName_text.Text;
                    string pwd2 = pwd1_text.Text;
                    if (pwd1.Equals(pwd2))
                    {
                        StreamWriter sw = new StreamWriter(dirpath);
                        sw.Write(GetMd5Str(pwd1));
                        sw.Close();
                    }
                    else
                    {
                       // if (pwd1.Equals("") || pwd2.Equals(""))
                             //MessageBox.Show("输入内容不能为空");
                        if (!pwd1.Equals(pwd2))
                             MessageBox.Show("两次输入的新密码不匹配");
                 
                        fileName_text.Focus();
                        pwd1_text.Focus();
                        return;
                    }
                }
                else                      //已经存在密码
                {
                    string pwd1 = fileName_text.Text;
                    string pwd2 = pwd1_text.Text;
                    string pwd3 = pwd2_text.Text;

                    string Md5pwd1 = GetMd5Str(pwd1);
                   
                    if (Md5pwd1.Equals(pwd0) && pwd2.Equals(pwd3))
                    {

                        StreamWriter sw = new StreamWriter(dirpath);
                        sw.Write(GetMd5Str(pwd2));
                        sw.Close();
                    }
                    else
                    {
                        //if (pwd1.Equals("") || pwd2.Equals("") || pwd3.Equals(""))
                            //MessageBox.Show("输入内容不能为空");
                        if(!Md5pwd1.Equals(pwd0))
                            MessageBox.Show("输入的原密码不对");
                        else if (!pwd2.Equals(pwd3))
                            MessageBox.Show("两次输入的新密码不匹配");

                        fileName_text.Focus();
                        pwd1_text.Focus();
                        return;
                    }
                }

                //编辑密码成功
                fileName_text.PasswordChar = '\0';
                label2.Visible = false;
                label3.Visible = false;
                label4.Visible = false;
                fileName_text.Visible = false;
                pwd1_text.Visible = false;
                pwd2_text.Visible = false;
                button_edit.Visible = true;
                button_new.Visible = true;
                fileName_text.Text = "";
                pwd1_text.Text = "";
                pwd2_text.Text = "";
                button_del.Text = "删除";
                button_pwd.Text = "密码";
                toolStripStatusLabel1.Text = "编辑密码成功,请选择该项后点击编辑按钮进行编辑";


            }
        }

        private void contrlServer()
        {
            StringBuilder sevName = new StringBuilder("BCCServer", 50);
            toolStripStatusLabel1.Text = "正在发布蓝牙服务.......";
            if (Server.BluetoothEnableDiscovery((IntPtr)0, true) == false)
            {
                MessageBox.Show("无法启动蓝牙发现", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            int b = Server.Advertise(sevName);
            switch (b)
            {
                case -1: toolStripStatusLabel1.Text = "socket初始化失败";
                    break;
                case -2: toolStripStatusLabel1.Text = "创建socket 出错，请检测时候插入蓝牙设备";
                    break;
                case -3: toolStripStatusLabel1.Text = "绑定socket 出错，请检测时候插入蓝牙设备";
                    break;
                case -4: toolStripStatusLabel1.Text = "监听socket 出错，请检测时候插入蓝牙设备";
                    break;
                case -5: toolStripStatusLabel1.Text = "发布服务出错，请检测时候插入蓝牙设备";
                    break;
                case -6: toolStripStatusLabel1.Text = "连接客户端出错";
                    break;
                default: toolStripStatusLabel1.Text = "连接成功！";
                    recvThread.Start();
                    break;

            }

        }
        private void rcv()
        {
            string xmlFile = checkedListBox_files.SelectedItem.ToString();
            string[] sArray = xmlFile.Split('.');
            xmlFile = sArray[0];
            xmlFile = xmlFile + ".xml";
            controler.xmlFile = xmlFile;
            controler.parentHandle = this.Handle;
            string tempStr, rcvStr = "", remainStr = "";
            string[] sCmdStr = null;
            bool bIsDeal;
            //bool isGoon = true;
            int result = 1;
            int c = 0;
            while (true)
            {
                tempStr = "";
                bIsDeal = false;
                int lenCmd = 0;
                try
                {
                    c = Server.Recve(ref tempStr, 300);
                    //计算tempStr的真实长度（针对中文情况）
                    int truelen = trueLength(tempStr, c);
                    tempStr = tempStr.Substring(0, truelen);
                    rcvStr = remainStr + tempStr;
                    //找到命令结束符':'
                    if (rcvStr.IndexOf(':') > -1)
                    {
                        bIsDeal = true;
                        sCmdStr = rcvStr.Split(':');
                        lenCmd = sCmdStr.Length-1;
                        if (rcvStr.EndsWith(":"))
                            remainStr = "";
                        else
                            remainStr = sCmdStr[lenCmd];
                    }
                    else
                    {
                        remainStr = rcvStr;
                        bIsDeal = false;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("蓝牙服务出错！请重新打开服务！"+ex.Message);
                    button_service_Click(new object(), new EventArgs());
                    return;
                }
                Console.WriteLine(rcvStr);
                if (bIsDeal)
                {
                    for (int i = 0; i < lenCmd; i++)
                        result = controler.ControlFuncation(sCmdStr[i]);
                    Thread.Sleep(msecond);
                    if (result!=1)
                    {
                        switch (result)
                        {
                            case -1: button_service_Click(new object(), new EventArgs());
                                     return;
                            case 2: notifyIcon1.ShowBalloonTip(3, "错误提醒：", "命令不完整", ToolTipIcon.Info);
                                     break;
                            case 3: notifyIcon1.ShowBalloonTip(3, "错误提醒：", "命令格式错误", ToolTipIcon.Info);
                                     break;
                        
                        }
                        
                    }
                }
                
            }            
        }
        private int trueLength(string str,int len)
        {
            int truelen = 0,asc;
            string strWord = "";
            for (int i=0; i < len; i++,truelen++)
            {
                strWord = str.Substring(i, 1);
                asc = Convert.ToChar(strWord);
                if (asc < 0 || asc > 127)
                    len--;
            }
            return truelen;
        }

        protected override void OnClosed(EventArgs e)
        {
            notifyIcon1.Visible = false;
            int b = Server.Close();
            System.Windows.Forms.Application.ExitThread();
            System.Environment.Exit(0);
            //notifyIcon1.Dispose();
            //doCmd("taskkill /im BCC.exe /f");
        }
        private void MainForm_Deactivate(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;
                this.Hide();
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
        }

        private void MenuItem_HideOrPlay_Click(object sender, EventArgs e)
        {
            if (this.MenuItem_Hide.Text.Equals("隐藏"))
            {
                this.WindowState = FormWindowState.Minimized;
                this.Hide();
                this.MenuItem_Hide.Text = "显示";
            }
            else if (this.MenuItem_Hide.Text.Equals("显示"))
            {
                if (this.WindowState == FormWindowState.Minimized)
                {
                    this.Visible = true;
                    this.WindowState = FormWindowState.Normal;
                }
                this.MenuItem_Hide.Text = "隐藏";
            }
        }

        private void MenuItem_Enable_Click(object sender, EventArgs e)
        {
            if (this.MenuItem_Enable.Text.Equals("注销"))
            {
                button_service_Click(sender, e);
                this.MenuItem_Enable.Text = "运行";
            }
            else if(this.MenuItem_Enable.Text.Equals("运行"))
            { 
                button_service_Click(sender, e);
                this.MenuItem_Enable.Text="注销";
            }
            
        }

        private void MenuItem_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        public void doCmd(string cmd)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.WriteLine(cmd);
            p.StandardInput.WriteLine("Exit");
            p.WaitForExit();
            p.Close();
        }

        private void SetAutoRun(string fileName, bool isAutoRun)
        {
            RegistryKey reg = null;
            try
            {
                if (!System.IO.File.Exists(fileName))
                    throw new Exception("该文件不存在!");
                String name = fileName.Substring(fileName.LastIndexOf(@"\") + 1);
                reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (reg == null)
                    reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                if (isAutoRun)
                    reg.SetValue(name, fileName);
                else
                    reg.SetValue(name, false);
                //lbl_autorunerr.Visible = false;
            }
            catch
            {
                //lbl_autorunerr.Visible = true;
                //throw new Exception(ex.ToString());
            }
            finally
            {
                if (reg != null)
                    reg.Close();
            }
        }

        private void MenuItem_SetRun_Click(object sender, EventArgs e)
        {
            if (this.MenuItem_SetRun.Text.Equals("开机启动"))
            {
                SetAutoRun(Application.ExecutablePath, true);
                this.MenuItem_SetRun.Text = "开机不启动";
            }
            else
            {
                SetAutoRun(Application.ExecutablePath, false);
                this.MenuItem_SetRun.Text = "开机启动";
            }
        }

        //返回MD5加密字符串 
        private string GetMd5Str(string myString)
        {
        //    MD5 md5 = new MD5CryptoServiceProvider();
        //    byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString);
        //    byte[] toData = md5.ComputeHash(fromData);
        //    string byteStr = null;
        //    for (int i = 0; i < toData.Length; i++)
        //        byteStr += toData[i].ToString("x");
        //    return byteStr;
            string byteStr="";
            MD5 md5 = MD5.Create();
            byte[]toData = md5.ComputeHash(Encoding.UTF8.GetBytes(myString));
            for (int i = 0; i < toData.Length; i++)
                byteStr += toData[i].ToString("x");
            return byteStr;

        }
        private void button_pwd_Click(object sender, EventArgs e)
        {
            if (button_pwd.Text.Equals("密码"))
            {
                fileName_text.PasswordChar = '*';
                string pwdfileName = "Password.txt";
                string dirpath = Application.StartupPath + "/data/" + pwdfileName;
                FileInfo file = new FileInfo(dirpath);


                string pwd0 = "d41d8cd98f0b24e980998ecf8427e";
                if (file.Exists)
                {
                    StreamReader sr = new StreamReader(dirpath);
                    pwd0 = sr.ReadToEnd();
                    sr.Close();
                }
                if (!pwd0.Equals("d41d8cd98f0b24e980998ecf8427e"))
                {
                    label2.Visible = true;
                    label3.Visible = true;
                    label4.Visible = true;
                    fileName_text.Visible = true;
                    pwd1_text.Visible = true;
                    pwd2_text.Visible = true;
                    button_edit.Visible = false;
                    button_new.Visible = false;
                    label2.Text = "原密码";
                    label3.Text = "新密码";
                    label4.Text = "再确认";
                    button_del.Text = "确定";
                    button_pwd.Text = "取消";
                    toolStripStatusLabel1.Text = "密码管理";
                }
                else
                {
                    label2.Visible = true;
                    label3.Visible = true;
                    
                    fileName_text.Visible = true;
                    pwd1_text.Visible = true;
                  
                    button_edit.Visible = false;
                    button_new.Visible = false;
                    label2.Text = "新密码";
                    label3.Text = "再确认";
      
                    button_del.Text = "确定";
                    button_pwd.Text = "取消";
                    toolStripStatusLabel1.Text = "密码管理";

                    StreamWriter sw = new StreamWriter(dirpath);
                    sw.Write("d41d8cd98f0b24e980998ecf8427e"); //默认为空
                    sw.Close();


                }
              
            }
            else if (button_pwd.Text.Equals("取消"))
            {
                fileName_text.PasswordChar = '\0';
                label2.Visible = false;
                label3.Visible = false;
                label4.Visible = false;
                fileName_text.Visible = false;
                pwd1_text.Visible = false;
                pwd2_text.Visible = false;
                button_edit.Visible = true;
                button_new.Visible = true;

                fileName_text.Text = "";
                pwd1_text.Text = "";
                pwd2_text.Text = "";
                button_del.Text = "删除";
                button_pwd.Text = "密码";
                toolStripStatusLabel1.Text = "编辑密码成功,请选择该项后点击编辑按钮进行编辑";
            }
        }

    }

}
